# coding=utf-8
# @Author:zcx
# @Time:2024/9/12 20:11
from PySide6.QtCore import Signal, QObject, QEvent
from PySide6.QtWidgets import QWidget, QApplication, QTextEdit, QVBoxLayout, QPushButton, QHBoxLayout
"""
在PYQT中，父控件可以通过两种方式响应子控件的事件：
    通过信号(signal)和槽函数(slot)机制连接子控件和父控件
    父控件可以通过设置eventFilter()方法来监听响应子控件的事件
"""

class ChildWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName('ChildWidget')
        self.layout = QHBoxLayout(self)
        self.child_button = QPushButton("Child")
        self.layout.addWidget(self.child_button)

class ParentWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.setObjectName('ParentWidget')
        self.layout = QHBoxLayout(self)
        # parent_button
        self.parent_button = QPushButton("Parent")
        self.parent_button.installEventFilter(self)
        # ChildWidget
        self.child = ChildWidget(self)
        self.child.child_button.installEventFilter(self)

        self.layout.addWidget(self.child)
        self.layout.addWidget(self.parent_button)
        self.layout.stretch(2)

    def eventFilter(self, obj, event):
        if obj == self.child.child_button and event.type() == QEvent.MouseButtonPress:
            print('ChildWidget eventFilter', event)
        elif obj == self.parent_button and event.type() == QEvent.MouseButtonPress:
            print('ParentWidget eventFilter', event)
        return super().eventFilter(obj, event)


if __name__ == '__main__':
    app = QApplication([])
    parent = ParentWidget()
    parent.show()
    app.exec()
